package com.zhang.web.servlet;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhang.pojo.ResultInfo;
import com.zhang.pojo.User;
import com.zhang.service.UserService;
import com.zhang.service.impl.UserServiceImpl;
import com.zhang.utils.JDBCUtils;
import com.zhang.utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String checkcode = req.getParameter("checkcode");
        ResultInfo info = new ResultInfo();


        //判断验证码是否正确
        HttpSession session = req.getSession();
        String code =(String) session.getAttribute("CHECKCODE_SERVER");
        if(checkcode.equalsIgnoreCase(code) && checkcode != " "){
            //验证码正确
            //判断用户名密码
            User user = userService.login(username, password);
            if(user != null){
                //将user保存到session域中
                session.setAttribute("user",user);
                //重庆定向到首页
               // resp.sendRedirect("/userpro/index.html");

                info.setFlag(true);
                JsonUtils.send(resp,info);
            }else{
                //密码错误
                info.setFlag(false);
                info.setErrorMsg("密码错误!");
                JsonUtils.send(resp,info);
            }
        }else {
            //验证码错误
            info.setFlag(false);
            info.setErrorMsg("验证码错误!");
            JsonUtils.send(resp,info);
        }


    }
}
